#include "HCSR04.h"

/**
 * @brief 超声波传感器初始化
 * 
 */
void HCSR04_Init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
    //tim2记录echo引脚从上升沿到下降沿所需的时间
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA,&GPIO_InitStructure);
    // GPIO_WriteBit(GPIOA,GPIO_Pin_5,Bit_RESET);

    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA,&GPIO_InitStructure);

    TIM_InternalClockConfig(TIM2);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStucture;
    TIM_TimeBaseStructInit(&TIM_TimeBaseInitStucture);
    TIM_TimeBaseInitStucture.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitStucture.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitStucture.TIM_Period = 65535;
    TIM_TimeBaseInitStucture.TIM_Prescaler = 719;
    TIM_TimeBaseInitStucture.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStucture);

    TIM_ICInitTypeDef TIM_ICInitStructure;
    TIM_ICStructInit(&TIM_ICInitStructure);
    TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;//通道
    TIM_ICInitStructure.TIM_ICFilter = 0XF;//滤波
    TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;//触发方式
    TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;//分频
    TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
    TIM_ICInit(TIM2,&TIM_ICInitStructure);

    TIM_PWMIConfig(TIM2,&TIM_ICInitStructure);

    TIM_SelectInputTrigger(TIM2,TIM_TS_TI1FP1);
    TIM_SelectSlaveMode(TIM2,TIM_SlaveMode_Reset);

    TIM_Cmd(TIM2,ENABLE);


    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);

    TIM_InternalClockConfig(TIM3);//tim3发出周期为60ms占空比为1/6000的pwm波

    TIM_TimeBaseInitStucture.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitStucture.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitStucture.TIM_Period = 71;
    TIM_TimeBaseInitStucture.TIM_Prescaler = 10000;
    TIM_TimeBaseInitStucture.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStucture);

    TIM_OCInitTypeDef TIM_OCInitStructure;
    TIM_OCStructInit(&TIM_OCInitStructure);
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = 10;
    TIM_OC1Init(TIM3,&TIM_OCInitStructure);

    TIM_Cmd(TIM3,ENABLE);
}

/**
 * @brief 返回超声波雷达的数据
 * 
 * @return uint16_t 传感器到障碍物之间声音来回所需的时间
 */
uint16_t HCSR04_GetDisdance(void)
{
    return TIM_GetCapture2(TIM2);
}




